<template>
  <div class="purchase-form">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="form"
    >
      <!-- 商品信息 -->
      <div class="product-info">
        <el-image :src="product.imageUrl" class="product-image" />
        <div class="product-details">
          <h3>{{ product.name }}</h3>
          <div class="price-info">
            <span class="current-price">¥{{ product.price }}</span>
            <span v-if="product.discountRate" class="original-price">
              ¥{{ (product.price / product.discountRate).toFixed(2) }}
            </span>
          </div>
        </div>
      </div>

      <!-- 购买数量 -->
      <el-form-item label="购买数量" prop="quantity">
        <el-input-number
          v-model="form.quantity"
          :min="1"
          :max="product.stockQuantity"
          @change="calculateTotal"
        />
      </el-form-item>

      <!-- 收货信息 -->
      <el-form-item label="收货人" prop="receiverName">
        <el-input v-model="form.receiverName" placeholder="请输入收货人姓名" />
      </el-form-item>

      <el-form-item label="手机号码" prop="receiverPhone">
        <el-input v-model="form.receiverPhone" placeholder="请输入手机号码" />
      </el-form-item>

      <el-form-item label="收货地址" prop="receiverAddress">
        <el-input
          v-model="form.receiverAddress"
          type="textarea"
          :rows="2"
          placeholder="请输入详细收货地址"
        />
      </el-form-item>

      <!-- 支付方式 -->
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-radio-group v-model="form.paymentMethod">
          <el-radio label="CREDIT">信用支付</el-radio>
          <el-radio label="INSTALLMENT" :disabled="!canUseInstallment">
            分期付款
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 分期信息 -->
      <template v-if="form.paymentMethod === 'INSTALLMENT'">
        <el-form-item label="分期期数" prop="installmentMonths">
          <el-select v-model="form.installmentMonths" @change="calculateMonthlyPayment">
            <el-option
              v-for="month in availableMonths"
              :key="month"
              :label="`${month}期`"
              :value="month"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="月供金额">
          <span class="monthly-payment">¥{{ monthlyPayment.toFixed(2) }}</span>
        </el-form-item>
      </template>

      <!-- 订单金额 -->
      <div class="order-amount">
        <div class="amount-item">
          <span>商品总额：</span>
          <span>¥{{ totalAmount.toFixed(2) }}</span>
        </div>
        <div v-if="discountAmount > 0" class="amount-item">
          <span>信用折扣：</span>
          <span class="discount">-¥{{ discountAmount.toFixed(2) }}</span>
        </div>
        <div class="amount-item total">
          <span>应付金额：</span>
          <span class="final-amount">¥{{ finalAmount.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交订单</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getProductDiscountInfo, checkInstallmentEligibility } from '@/api/product'

export default {
  name: 'PurchaseForm',
  props: {
    product: {
      type: Object,
      required: true
    }
  },
  emits: ['submit', 'cancel'],
  setup(props, { emit }) {
    const formRef = ref(null)
    const canUseInstallment = ref(false)
    const monthlyPayment = ref(0)
    const totalAmount = ref(0)
    const discountAmount = ref(0)
    const finalAmount = ref(0)

    const form = reactive({
      quantity: 1,
      receiverName: '',
      receiverPhone: '',
      receiverAddress: '',
      paymentMethod: 'CREDIT',
      installmentMonths: 3
    })

    const rules = {
      quantity: [
        { required: true, message: '请选择购买数量', trigger: 'change' }
      ],
      receiverName: [
        { required: true, message: '请输入收货人姓名', trigger: 'blur' }
      ],
      receiverPhone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      receiverAddress: [
        { required: true, message: '请输入收货地址', trigger: 'blur' }
      ],
      paymentMethod: [
        { required: true, message: '请选择支付方式', trigger: 'change' }
      ],
      installmentMonths: [
        { required: true, message: '请选择分期期数', trigger: 'change' }
      ]
    }

    const availableMonths = computed(() => {
      return props.product.isInstallmentAvailable ? [3, 6, 12, 24] : []
    })

    // 计算订单金额
    const calculateTotal = async () => {
      try {
        const discountInfo = await getProductDiscountInfo(props.product.id)
        totalAmount.value = props.product.price * form.quantity
        discountAmount.value = totalAmount.value * (1 - discountInfo.discountRate)
        finalAmount.value = totalAmount.value - discountAmount.value
        calculateMonthlyPayment()
      } catch (error) {
        ElMessage.error('获取折扣信息失败')
      }
    }

    // 计算月供金额
    const calculateMonthlyPayment = () => {
      if (form.paymentMethod === 'INSTALLMENT') {
        monthlyPayment.value = finalAmount.value / form.installmentMonths
      }
    }

    // 检查分期付款资格
    const checkInstallment = async () => {
      try {
        canUseInstallment.value = await checkInstallmentEligibility(props.product.id)
      } catch (error) {
        ElMessage.error('检查分期付款资格失败')
      }
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        emit('submit', {
          ...form,
          totalAmount: totalAmount.value,
          discountAmount: discountAmount.value,
          finalAmount: finalAmount.value,
          monthlyPayment: monthlyPayment.value
        })
      } catch (error) {
        ElMessage.error('请完善订单信息')
      }
    }

    // 取消订单
    const handleCancel = () => {
      emit('cancel')
    }

    onMounted(() => {
      calculateTotal()
      checkInstallment()
    })

    return {
      formRef,
      form,
      rules,
      canUseInstallment,
      availableMonths,
      monthlyPayment,
      totalAmount,
      discountAmount,
      finalAmount,
      calculateTotal,
      calculateMonthlyPayment,
      handleSubmit,
      handleCancel
    }
  }
}
</script>

<style lang="scss" scoped>
.purchase-form {
  .form {
    .product-info {
      display: flex;
      gap: 20px;
      margin-bottom: 20px;
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 4px;

      .product-image {
        width: 100px;
        height: 100px;
        border-radius: 4px;
      }

      .product-details {
        flex: 1;

        h3 {
          margin: 0 0 10px;
          font-size: 16px;
        }

        .price-info {
          .current-price {
            font-size: 20px;
            color: #f56c6c;
            font-weight: bold;
          }

          .original-price {
            margin-left: 10px;
            font-size: 14px;
            color: #999;
            text-decoration: line-through;
          }
        }
      }
    }

    .order-amount {
      margin: 20px 0;
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 4px;

      .amount-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        font-size: 14px;

        &.total {
          margin-top: 10px;
          padding-top: 10px;
          border-top: 1px solid #dcdfe6;
          font-size: 16px;
          font-weight: bold;

          .final-amount {
            color: #f56c6c;
            font-size: 20px;
          }
        }

        .discount {
          color: #67c23a;
        }
      }
    }

    .form-actions {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      margin-top: 20px;
    }
  }
}
</style> 